package OrderRefundService

import (
	"context"
	"errors"
	"gdshop-admin-go-api/app/entity"
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"github.com/syyongx/php2go"
	"time"
)

func SubmitHandle(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	status := r.GetInt("status", 0)
	if status == 0 {
		return response.FailByRequestMessage(r, "status 错误")
	}
	allowStatus := []int{
		2, 3,
	}
	if !php2go.InArray(status, allowStatus) {
		return response.FailByRequestMessage(r, "status 不允许当前值，可用范围："+gconv.String(allowStatus))
	}

	handleRemark := r.GetString("handle_remark", "")
	if status == 2 {
		if len(handleRemark) < 1 {
			return response.FailByRequestMessage(r, "拒绝请输入拒绝理由")
		}
	}

	var orModel *entity.OrderRefund
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "order_refund").Where("id", req.Id).Struct(&orModel)
	if err != nil {
		return response.FailByRequestMessage(r, "找不到退货信息")
	}
	if orModel.Status != 1 {
		return response.FailByRequestMessage(r, "当前状态不允许处理")
	}

	err = g.DB().Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
		update, err := tx.Model("order_sub").Where("id", orModel.OrderSubId).Update(g.Map{
			"refund_status": status,
		})
		if err != nil {
			return err
		}
		affected, err := update.RowsAffected()
		if err != nil {
			return err
		}
		if affected < 1 {
			return errors.New("更新失败")
		}
		update, err = tx.Model("order_refund").Where("id", req.Id).Update(g.Map{
			"handle_remark":   handleRemark,
			"handle_time":     time.Now().Unix(),
			"handle_admin_id": req.AdminId,
			"status":          status,
		})
		if err != nil {
			return err
		}
		affected, err = update.RowsAffected()
		if err != nil {
			return err
		}
		if affected < 1 {
			return errors.New("更新失败")
		}

		_, err = tx.Model("order_refund_log").InsertAndGetId(g.Map{
			"order_id":        orModel.OrderId,
			"order_sub_id":    orModel.OrderSubId,
			"order_refund_id": req.Id,
			"handle_remark":   handleRemark,
			"handle_time":     time.Now().Unix(),
			"handle_admin_id": req.AdminId,
			"status":          status,
		})
		if err != nil {
			return err
		}

		return nil
	})
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}

	return response.SuccessByRequestMessage(r, "处理成功")
}
